package com.zhao.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class HttpClientUtil {

	@Value("${baidu.apis.apikey}")
	private String apiKey;

	/**
	 * 
	 */
	public void upload() {
		HttpClient httpClient = HttpClients.createDefault();
		try {
			HttpPost post = new HttpPost();
			post.setURI(new URI("http://127.0.0.1:8080/batchUpload"));
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.addPart("file", new FileBody(new File("d:/1.txt")));
			builder.addPart("file", new FileBody(new File("d:/2.txt")));
			builder.addPart("string", new StringBody("String1", ContentType.APPLICATION_JSON));
			post.setEntity(builder.build());
			HttpClientContext request = new HttpClientContext();
			httpClient.execute(post, request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param uri
	 * @param nvps
	 * @return
	 */
	public String get(String uri, final NameValuePair... nvps) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		if (StringUtils.isEmpty(apiKey)) {
			apiKey = "37c6b6d5154b5057fe861fb450afa9ae";
		}
		HttpUriRequest get = RequestBuilder.get().setUri(uri).addHeader("apikey", apiKey).addParameters(nvps).build();
		ResponseHandler<String> rh = new ResponseHandler<String>() {
			@Override
			public String handleResponse(final HttpResponse response) throws IOException {
				StatusLine statusLine = response.getStatusLine();
				HttpEntity entity = response.getEntity();
				if (statusLine.getStatusCode() >= 300) {
					throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
				}
				if (entity == null) {
					throw new ClientProtocolException("Response contains no content");
				}
				BufferedReader reader = null;
				String result = null;
				StringBuffer sbf = new StringBuffer();
				reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
				String strRead = null;
				while ((strRead = reader.readLine()) != null) {
					sbf.append(strRead);
					sbf.append("\r\n");
				}
				reader.close();
				result = sbf.toString();
				return result;
			}
		};
		String str = null;
		try {
			str = httpClient.execute(get, rh);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
